<!-- 
	动态组件：秒杀组件 TODO
	props: 
		data: 组件数据
		
	action:
		
 -->
<template>
    <view class="dynamic-category">
        <tab-bar-seckill
            v-if="data.SeckillShowTimeBar"
            :tabs="tabs"
            @clickTab="clickTab"
            :tabIndex="tabIndex"></tab-bar-seckill>
        <view
            :class="{
                'style-2': data.SeckillStyle == 'img-sm',
            }">
            <view
                class="dynamic-seckill"
                @click="goDetail(item)"
                :class="{
                    'style-big': data.SeckillStyle == 'img-lg',
                }"
                v-for="(item, index) in proList"
                v-if="index <= moreNum - 1">
                <view class="seckill-img">
                    <image
                        :mode="data.SeckillStyle == 'img-lg' ? 'widthFix' : 'aspectFill'"
                        class="seckill-img-pro"
                        :src="easyGetImgUrl(item.ProductImage)"></image>
                    <image
                        mode="aspectFill"
                        v-if="data.SeckillShowCorner"
                        class="seckill-img-icon"
                        src="@/static/img/icon-ms.png"></image>
                </view>
                <view class="seckill-main">
                    <view class="main-titel text-show-line-2" v-if="data.SeckillShowName">{{ item.ProductName }}</view>
                    <view class="main-titel1 text-show-line-2">{{ item.DisplayAttribute?item.DisplayAttribute:'默认规格' }}</view>
                    <view class="msib-labels" v-if="data.SeckillShowLabel && item.TagList">
                        <text class="msib-label" v-for="tag in item.TagList">{{ tag.TagName }}</text>
                    </view>
                    <view class="msib-countdown"
                        ><text class="impose" v-if="data.SeckillShowMax">限{{ item.Quantity }}件</text
                        >{{ item.CountDownStr }}</view
                    >
                    <view class="mod-progress" v-if="data.SeckillShowProgress">
                        <view class="mod-progress__content">
                            <view class="mod-progress__track">
                                <view class="mod-progress__runway" :style="'width:' + item.percent + '%'"></view>
                            </view>
                        </view>
                        <view class="mod-progress__txt ng-binding">已秒{{ item.percent }}%</view>
                    </view>
                    <view class="price">
                        <view class="price-l" v-if="data.SeckillShowPrice"
                            ><view class="new-price"><text>￥</text>{{ item.Price }}</view
                            ><view class="old-price">￥{{ item.OriginalPrice }}</view></view
                        >
                        <view class="seckill-btn" :class="item.SeckillBtnStyle">{{ item.SeckillBtn }}</view>
                    </view>
                </view>
            </view>
        </view>
        <view
            v-if="data.SeckillShowMore && proList.length > data.SeckillPageSize && moreNum != 100"
            class="more"
            @click="lookmore"
            >查看更多>></view
        >
    </view>
</template>

<script>
import { GetNowTime } from "@/service/api/activity.js"
import { GetSeckillStartTimeList, GetSeckillGoodsListByStartTime, GetSeckillGoodsList } from "@/service/api/seckill.js"
import storage from "@/uni-sub-base/utils/storage.js"
import tabBarSeckill from "@/uni-sub-base/components/dynamic/tab-bar-seckill.vue"
export default {
    props: {
        data: {
            type: Object,
            default: () => {},
        },
    },
    components: {
        tabBarSeckill,
    },
    data() {
        return {
            currStartTime: null,
            longago: false,
            tabIndex: 0, // 当前tab的下标
            tabs: [],
            nowTime: null,
            proList: [],
            moreNum: 0,
        }
    },
    mounted() {
        this.moreNum = this.data.SeckillPageSize
        this.gettabs()
        this.setInterval()
    },
    methods: {
        goDetail(item) {
            let token = storage.getCache("token")
            if (!token || token == "") {
                this.$showModal({ show: true })
                return false
            }
			if(item.SeckillBtn !="已结束"){
				this.easyGoTo(`/pages_shop/packet/product/seckillDetail?id=${item.ActivityId}`)
			}
        },
        gettabs() {
            var _this = this
            GetSeckillStartTimeList().then((res) => {
                if (res.State == 1) {
                    if (res.Data.length > 0) {
                        GetNowTime().then((rsp) => {
                            if (res.State == 1) {
                                if (this.data.SeckillShowTimeBar) {
                                    var todayTime = new Date(rsp.Data.replace(/-/g, "/"))
                                    todayTime.setHours(0)
                                    todayTime.setMinutes(0)
                                    todayTime.setSeconds(0)
                                    todayTime.setMilliseconds(0)
                                    var oneday = 1000 * 60 * 60 * 24
                                    // 昨天
                                    var yesterdayTime = new Date(todayTime - oneday)
                                    var tomorrowTime = new Date(todayTime.getTime() + oneday)
                                    var towDayTime = new Date(todayTime.getTime() + 2 * oneday)
                                    var nowTime = new Date(rsp.Data.replace(/-/g, "/"))
									res.Data.reverse()
                                    var data = res.Data
                                    for (var i = 0; i < data.length; i++) {
                                        let time = new Date(data[i].replace(/-/g, "/"))
                                        let datetime =
                                            time.getHours() +
                                            ":" +
                                            (time.getMinutes() > 9
                                                ? time.getMinutes().toString()
                                                : "0" + time.getMinutes())
                                        if (time < yesterdayTime) {
                                            if (_this.longago == false) {
                                                _this.tabs.push({
                                                    isstart: true,
                                                    timeTxt: "更早",
                                                    time: yesterdayTime,
                                                    active: false,
                                                })
                                            }
                                            _this.longago = true
                                        }
                                        if (time >= yesterdayTime && time < todayTime) {
                                            _this.tabs.push({
                                                isstart: true,
                                                timeTxt: "昨日" + datetime,
                                                time: time,
                                                active: false,
                                            })
                                        }
                                        if (time >= todayTime && time < tomorrowTime) {
                                            if (nowTime >= time) {
                                                _this.tabs.push({
                                                    isstart: true,
                                                    timeTxt: datetime,
                                                    time: time,
                                                    active: false,
                                                })
                                            } else {
                                                _this.tabs.push({
                                                    isstart: false,
                                                    timeTxt: datetime,
                                                    time: time,
                                                    active: false,
                                                })
                                            }
                                        }
                                        if (time >= tomorrowTime && time < towDayTime) {
                                            _this.tabs.push({
                                                isstart: false,
                                                timeTxt: "明日" + datetime,
                                                time: time,
                                                active: false,
                                            })
                                        }
                                    }
									_this.tabs.push({
									    isstart: false,
									    timeTxt: '已结束',
									    time: '',
									    active: false,
									    isEnd: true,
									})
                                    //设置默认选中的时间点
                                    if (_this.tabs.length > 0) {
                                        if (_this.tabs.length == 1) {
                                            _this.changeStartTime(_this.tabs[0])
                                        } else {
                                            if (!_this.tabs[0].isstart) {
                                                _this.changeStartTime(_this.tabs[0])
                                            } else if (_this.tabs[_this.tabs.length - 1].isstart) {
                                                _this.changeStartTime(_this.tabs[_this.tabs.length - 1])
                                            } else {
                                                for (var i = 1; i <= _this.tabs.length - 1; i++) {
                                                    if (!_this.tabs[i].isstart && _this.tabs[i - 1].isstart) {
                                                        _this.changeStartTime(_this.tabs[i - 1])
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    for (var i = 1; i <= _this.tabs.length - 1; i++) {
                                        if (_this.tabs[i].active) {
                                            this.tabIndex = i
                                        }
                                    }
									console.log(_this.tabs)
                                    this.getDatas(this.tabs[this.tabIndex]) //有上面时间栏
                                } else {
                                    this.getNoTimeDatas() //隐藏时间栏
                                }
                            } else {
                                this.easyToast(res.Msg)
                            }
                        })
                    } else {
                        this.setLoadBack()
                    }
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        changeStartTime(item) {
            if (this.currStartTime) this.currStartTime.active = false
            this.currStartTime = item
            this.currStartTime.active = true
        },
        getDatas(item) {
            let parm = {
                pageIndex: 1,
                pageSize: 100,
            }
            if (item.timeTxt == "更早") {
                parm.isLongAgo = true
            } else {
                parm.isLongAgo = false
            }
			if(item.time){
				parm.startTime = item.time
			}else{
				parm.isEnd = item.isEnd
			}
            let webInfo = storage.getCache("webInfo")
            if (webInfo.IsSelectWarehouse == 1) {
                let warehouse = storage.getCache("warehouse")
                parm.warehouseId = warehouse.WarehouseId
            }
            GetSeckillGoodsListByStartTime(parm).then((res) => {
                let data = res.Data
                for (var i = 0; i < data.length; i++) {
                    //data[i].restTime = (new Date(data[i].EndTime) - new Date());
                    var percent = (data[i].UseQty / data[i].Quantity) * 100
                    if (data[i].UseQty > 0 && percent.toFixed(1) < 1) {
                        data[i].percent = 1
                    } else if (99 <= percent.toFixed(1) && percent.toFixed(1) < 100) {
                        data[i].percent = 99
                    } else {
                        data[i].percent = percent.toFixed(0)
                    }
                    data[i].timeStatus = 0
                    data[i].SeckillBtnStyle = ""
                    data[i].SeckillBtn = ""
                    data[i].CountDownStr = ""
                }
                this.proList = data
            })
            this.setLoadBack()
        },
        getNoTimeDatas(item) {
            let parm = {
                pageIndex: 1,
                pageSize: 100,
            }
            GetSeckillGoodsList(parm).then((res) => {
                let data = res.Data
                for (var i = 0; i < data.length; i++) {
                    //data[i].restTime = (new Date(data[i].EndTime) - new Date());
                    var percent = (data[i].UseQty / data[i].Quantity) * 100
                    if (data[i].UseQty > 0 && percent.toFixed(1) < 1) {
                        data[i].percent = 1
                    } else if (99 <= percent.toFixed(1) && percent.toFixed(1) < 100) {
                        data[i].percent = 99
                    } else {
                        data[i].percent = percent.toFixed(0)
                    }
                    data[i].timeStatus = 0
                    data[i].SeckillBtnStyle = ""
                    data[i].SeckillBtn = "立即秒杀"
                    data[i].CountDownStr = ""
                }
                this.proList = data
            })
            this.setLoadBack()
        },
        setInterval() {
            var that = this
            //当前时间
            GetNowTime().then((rsp) => {
                if (rsp.State == 1) {
                    that.nowTime = new Date(rsp.Data.replace(/-/g, "/")).getTime()
                    setInterval((e) => {
                        that.nowTime += 1000
                        that.setCountDown()
                    }, 1000)
                    // that.setCountDown(that.proList);
                }
            })
        },
        //秒杀设置倒计时
        setCountDown() {
            if (!this.nowTime || !this.proList.length) {
                return
            }
            this.proList.forEach((item) => {
                var s = ""
                item.timeStatus = 0
                var diff = new Date(item.EndTime.replace(/-/g, "/")).getTime() - this.nowTime //时间差的毫秒数
                //未结束
                if (diff >= 0) {
                    //未开始
                    if (new Date(item.StartTime.replace(/-/g, "/")).getTime() - this.nowTime > 0) {
                        s = ""
                        item.timeStatus = 0
                        if (item.IsShowRemind == 1) {
                            item.SeckillBtnStyle = "msib-btn"
                            // if (item.UserOperationState && item.UserOperationState == 1) {
                            //     item.SeckillBtn = "取消提醒"
                            // } else {
                            //     item.SeckillBtn = "设置提醒"
                            // }
                            item.SeckillBtnStyle = "msib-btn-disabled"
                            item.SeckillBtn = "未开始"
                        } else {
                            item.SeckillBtnStyle = "msib-btn-disabled"
                            item.SeckillBtn = "未开始"
                        }
                        //diff = new Date(item.StartTime.replace(/-/g, '/')).getTime() - this.nowTime;
                        var startTime = new Date(item.StartTime.replace(/-/g, "/"))
                        var nowTime = new Date(this.nowTime)
                        if (this.data.SeckillShowTimeBar) {
                            item.CountDownStr = ""
                        } else {
                            if (startTime.toDateString() === nowTime.toDateString()) {
                                item.CountDownStr = "今日 " + startTime.format("HH:mm:ss") + " 开始"
                            } else if (
                                startTime.toDateString() === new Date(this.nowTime + 24 * 60 * 60 * 1000).toDateString()
                            ) {
                                item.CountDownStr = "明日 " + startTime.format("HH:mm:ss") + " 开始"
                            } else {
                                item.CountDownStr = startTime.format("MM月dd日 HH:mm:ss") + " 开始"
                            }
                        }
                    } else {
                        s = "距结束"
                        item.SeckillBtnStyle = "msib-btn"
                        item.SeckillBtn = "立即秒杀"
                        item.timeStatus = 1

                        //计算出相差天数
                        var days = Math.floor(diff / (24 * 3600 * 1000))
                        //计算出小时数
                        var leave1 = diff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
                        var hours = Math.floor(leave1 / (3600 * 1000))
                        //计算相差分钟数
                        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
                        var minutes = Math.floor(leave2 / (60 * 1000))
                        //计算相差秒数
                        var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
                        var seconds = Math.round(leave3 / 1000)
                        item.CountDown = {
                            Days: (days > 9 ? "" : "0") + days,
                            Hours: (hours > 9 ? "" : "0") + hours,
                            Minutes: (minutes > 9 ? "" : "0") + minutes,
                            Seconds: (seconds > 9 ? "" : "0") + seconds,
                        }
                        item.CountDownStr =
                            s +
                            item.CountDown.Days +
                            "天" +
                            item.CountDown.Hours +
                            ":" +
                            item.CountDown.Minutes +
                            ":" +
                            item.CountDown.Seconds
                    }
                } else {
                    item.CountDown = {
                        Days: "00",
                        Hours: "00",
                        Minutes: "00",
                        Seconds: "00",
                    }
                    s = "已结束"
                    item.Status = 2
                    item.CountDownStr = s
                    item.SeckillBtnStyle = "msib-btn-disabled"
                    item.SeckillBtn = "已结束"
                }
            })
        },
        lookmore() {
            this.moreNum = 100
        },
        //组件加载完成
        setLoadBack() {
            this.$emit("loadBack", this.data.index)
        },
        clickTab(index) {
            if (this.tabIndex != index) {
                this.tabIndex = index
            }
            this.getDatas(this.tabs[this.tabIndex])
        },
    },
}
</script>

<style lang="scss" scope>
@import "@/uni-sub-base/components/dynamic/style/dynamic.scss";
.mod-progress {
    display: flex;
    height: 40rpx;
    line-height: 40rpx;
}
.mod-progress__content {
    position: relative;
    flex: 1;
    display: flex;
    align-items: center;
    .mod-progress__track {
        position: relative;
        width: 100%;
        height: 8rpx;
        overflow: hidden;
        background: #e5e5e5;
        border-radius: 10rpx;
        .mod-progress__runway {
            height: 100%;
            background: $app-color-main;
            border-radius: 3rpx;
            position: absolute;
            top: 50%;
            transform: translate(0, -50%);
        }
    }
}
.mod-progress__txt {
    margin: 0 0 0 10rpx;
    font-size: 24rpx;
    color: #999;
}
.dynamic-seckill {
    display: flex;
    padding: 24rpx;
    margin-bottom: 20rpx;
    background: #fff;
}
.seckill-img {
    position: relative;
    .seckill-img-pro {
        width: 225rpx;
        height: 225rpx;
        margin-right: 20rpx;
    }
    .seckill-img-icon {
        position: absolute;
        top: 0;
        left: 20rpx;
        display: block;
        width: 60rpx;
        height: 36rpx;
    }
}
.seckill-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .main-titel {
        font-size: 30rpx;
        color: $color-gray-1;
    }
	.main-titel1{
		font-size: 24rpx;
		color: $color-gray-3;
		margin-top: -10rpx;
	}
    .msib-labels {
        .msib-label {
            display: inline-block;
            height: 40rpx;
            line-height: 36rpx;
            padding: 0 10rpx;
            margin: 0 10rpx 0 0;
            font-size: 24rpx;
            color: $app-color-main;
            border: 1rpx solid $app-color-main;
            border-radius: 6rpx;
        }
    }
    .msib-countdown {
        font-size: 24rpx;
        color: $color-gray-3;
        .impose {
            color: $color-gray-3;
            padding-right: 20rpx;
        }
    }
}
.price {
    display: flex;
    justify-content: space-between;
    .price-l {
        display: flex;
        align-items: center;
        justify-content: flex-start;
    }
}
.new-price {
    font-size: 30rpx;
    color: $app-color-main;
    font-weight: bold;
    text {
        font-size: 24rpx;
        color: $app-color-main;
    }
}
.old-price {
    margin: 0 0 0 12rpx;
    font-size: 24rpx;
    color: $color-gray-3;
    text-decoration: line-through;
}
.seckill-btn {
    height: 50rpx;
    line-height: 50rpx;
    padding: 0 24rpx;
    font-size: 24rpx;
    color: #fff;
    border-radius: 30rpx;
}
.msib-btn-disabled {
    color: $color-gray-3;
    background: none;
    padding: 0;
}
.msib-btn {
    background-color: $app-color-main;
}
.more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 14rpx;
    color: $color-gray-3;
    font-size: 28rpx;
}
.style-big {
    margin: 24rpx;
    padding: 0rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
    border-radius: 20rpx;
    flex-direction: column;
    .seckill-img-pro {
        width: 100%;
        margin: 0;
    }
    .seckill-img-icon {
        position: absolute;
        top: 0;
        left: 20rpx;
        display: block;
        width: 90rpx;
        height: 54rpx;
    }
    .seckill-main {
        padding: 24rpx;
        .main-titel {
            margin-bottom: 20rpx;
        }
    }
    .price {
        margin-top: 20rpx;
    }
}
.style-2 {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 24rpx;
    .dynamic-seckill {
        width: calc(50% - 10rpx);
        padding: 0rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
        overflow: hidden;
        border-radius: 20rpx;
        flex-direction: column;
        .seckill-img-pro {
            width: 100%;
            height: 300rpx;
        }
        .seckill-main {
            padding: 20rpx;
            .msib-countdown {
                font-size: 20rpx;
                .impose {
                    padding-right: 10rpx;
                }
            }
            .main-titel {
                margin-bottom: 20rpx;
            }
            .price {
                display: block;
                .price-l {
                    display: flex;
                    align-items: center;
                    justify-content: flex-start;
                }
                .seckill-btn {
                    display: block;
                    width: 100rpx;
                    margin: 10rpx auto;
                    text-align: center;
                }
            }
        }
    }
}
</style>
